<!DOCTYPE html>
<html>
<#include "_inc/constants.ftl" />
<head>
    <title></title>
    <!-- For-Mobile-Apps-and-Meta-Tags -->
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=false" name="viewport" />
    <meta name="keywords"
          content="Fortune Estates Widget Responsive, Login Form Web Template, Flat Pricing Tables, Flat Drop-Downs, Sign-Up Web Templates, Flat Web Templates, Login Sign-up Responsive Web Template, SmartPhone Compatible Web Template, Free Web Designs for Nokia, Samsung, LG, Sony Ericsson, Motorola Web Design"/>
    <link href="css/bootstrap.css" type="text/css" rel="stylesheet" media="all">
    <link rel="stylesheet" href="css/ken-burns.css" type="text/css" media="all"/>
    <!--//pop-up-box -->
    <!-- web-fonts -->
    <link href='http://fonts.googleapis.com/css?family=Abel' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900,900italic'
          rel='stylesheet' type='text/css'>
    <!-- //web-fonts -->
    <link rel="stylesheet" href="css/weui.min.css">
    <link rel="stylesheet" href="css/jquery-weui.css">
    <link rel="stylesheet" href="css/demos.css">
    <link rel="stylesheet" href="css/common.css">
    <style>
        body {
            width: 100%;
            margin: 0 auto;
        }

        p {
            margin: 0 0 0;
        }

        h1 {
            margin: 0 0 0;
        }

        .name {
            font-size: 45px;
        }

        .price {
            margin-top: 21px;
            font-size: 44px;
        }

        .justify {
            justify-content: center;
        }

        .align {
            align-items: center;
        }

        /*媒体查询：注意and后面空格的添加*/
        /*iphone: w < 768px*/

        @media screen and (max-width: 375px) {
            body {
                width: 100%;
            }

            .name {
                font-size: 16px;
                font-family: "微软雅黑";
            }

            .price {
                margin-top: 3px;
                font-size: 14px;
            }
        }

        @media screen and (max-width: 425px) and (min-width: 376px) {
            body {
                width: 100%;
            }

            .name {
                font-size: 21px;
            }

            .price {
                margin-top: 6px;
                font-size: 19px;
            }
        }

        @media screen and (max-width: 597px) and (min-width: 426px) {
            body {
                width: 100%;
            }

            .name {
                font-size: 25px;
            }

            .price {
                margin-top: 9px;
                font-size: 24px;
            }
        }

        @media screen and (max-width: 768px) and (min-width: 597px) {
            body {
                width: 100%;
            }

            .name {
                font-size: 30px;
            }

            .price {
                margin-top: 12px;
                font-size: 29px;
            }
        }

        /*pad: w >= 768  && w< 992*/

        @media screen and (max-width: 992px) and (min-width: 767px) {
            body {
                width: 100%;
            }

            .name {
                font-size: 35px;
            }

            .price {
                margin-top: 15px;
                font-size: 34px;
            }
        }

        /*中等屏幕   w >= 992  && w<1200*/

        @media screen and (max-width: 1200px) and (min-width: 992px) {
            body {
                width: 100%;
            }

            .name {
                font-size: 40px;
            }

            .price {
                margin-top: 18px;
                font-size: 39px;
            }
        }
    </style>
</head>

<body class="bg" style="background-color: rgb(255,250,221);">
<div class="agile-main">
    <div>
        <img src="images/ttt.png" style="width: 100%; height: 40px;">
    </div>
    <div class="content-wrap">
        <div class="content" style="padding-left: 20px;padding-right: 20px;margin-top: 20px;">
            <div id="prompt" style="margin-top: 10px;display: none;text-align: center;width: 100%;">
                您还没有选购奶茶
            </div>

            <div id="payDetail" style="margin-top: 20px;">
                <div class="weui-cells">
                    <div class="weui-cell">
                        <div class="weui-cell__bd">
                            <p>总价</p>
                        </div>
                        <span style="color: #999;">￥</span>
                        <div id="tprice" class="weui-cell__ft">0.00</div>
                    </div>
                    <div class="weui-cell">
                        <div class="weui-cell__bd">
                            <p>需支付</p>
                        </div>
                        <span style="color: #999;">￥</span>
                        <div id="actualPay" class="weui-cell__ft">0.00</div>
                    </div>
                </div>
            </div>

            <div id="groupBtn" style="margin-top: 20px;">
                <div class="weui-flex">
                    <div class="weui-flex__item weui-flex justify align">
                        <div class="placeholder">
                            <button id="back" type="button" class="btn">返回再挑</button>
                        </div>
                    </div>
                    <div class="weui-flex__item weui-flex justify align">
                        <div class="placeholder">
                            <button id="wxPay" type="button" class="btn">微信支付</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div style="height: 100px;"></div>
        <#include "_inc/menufooter.ftl" />
    </div>
</div>

<!-- js -->
<script src="js/jquery.min.js"></script>
<!-- //js -->
<script src="js/jquery.magnific-popup.js" type="text/javascript"></script>
<script src="js/classie.js"></script>
<script src="js/jquery.nicescroll.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/fastclick.js"></script>
<script src="js/jquery-weui.min.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script src="js/utils.js"></script>
<script src="js/store.js"></script>
<script>

    wx.config({
        debug: false,
        appId: '${appid}',
        timestamp: ${timestamp},
        nonceStr: '${noncestr}',
        signature: '${signature}',
        jsApiList: [
            'closeWindow',
            'chooseWXPay'
        ]
    });

    //写入缓存cache
    function writecache() {
        var content = "";
        $('.price').each(function (index) {
            var num = parseInt($(this).parent().parent().next().children(".placeholder").children(".weui-count").children("input").val() || "0");
            var cprice = $(this).text().substring(1);
            var price = $(this).prev().prev().prev().val();
            var pid = $(this).prev().prev().prev().prev().val();
            var name = $(this).prev().prev().html();
            var enname = $(this).prev().val();
            if (index == $(".price").length - 1) {
                content += '{"name":"' + name + '","num":"' + num + '","pid":"' + pid + '","cprice":"' + cprice + '","price":"' + price + '","enname":"' + enname + '"}';
            } else {
                content += '{"name":"' + name + '","num":"' + num + '","pid":"' + pid + '","cprice":"' + cprice + '","price":"' + price + '","enname":"' + enname + '"},';
            }
        });
        var json = '{"list":[' + content + ']}';
        window.localStorage.setItem("list${mach}", json);
    }

    $(document).ready(function () {
        FastClick.attach(document.body);
        //加载缓存
        load();
        //计算总价
        var cprice = 0;
        var count = 0;
        $('.price').each(function () {
            num = parseInt($(this).parent().parent().next().children(".placeholder").children(".weui-count").children("input").val() || "0");
            cprice += $(this).text().substring(1) * num;
        });
        $("#tprice").html(cprice.toFixed(2));
        var actualPay = cprice;
        $("#actualPay").html(actualPay.toFixed(2));
    });

    var MAX = 99, MIN = 1;

    //减
    $("body").on("click", ".weui-count__decrease", function (e) {
        var $input = $(e.currentTarget).parent().find('.weui-count__number');
        var number = parseInt($input.val() || "0") - 1;
        if (number < MIN) {
            number = MIN;
        } else {
            var danjia = $(this).parent().parent().parent().prev().children().children(".price").text().substring(1);
            var a = $("#tprice").html(); //获取当前所选总价
            $("#tprice").html((a * 1 - danjia * 1).toFixed(2)); //计算当前所选总价
            var actualPay = $("#tprice").html() * 1;
            $("#actualPay").html(actualPay.toFixed(2));
        }
        $input.val(number);
        writecache();
    });
    //加
    $("body").on("click", ".weui-count__increase", function (e) {
        var $input = $(e.currentTarget).parent().find('.weui-count__number');
        var number = parseInt($input.val() || "0") + 1;
        if (number > MAX) number = MAX;
        $input.val(number);
        var danjia = $(this).parent().parent().parent().prev().children().children(".price").text().substring(1);
        var a = $("#tprice").html(); //获取当前所选总价
        $("#tprice").html((a * 1 + danjia * 1).toFixed(2)); //计算当前所选总价
        var actualPay = $("#tprice").html() * 1;
        $("#actualPay").html(actualPay.toFixed(2));
        writecache();
    });

    //删除
    $("body").on("click", ".delete", function () {
        var danjia = $(this).parent().parent().parent().prev().children().children(".price").text().substring(1);
        var num = $(this).parent().prev().children("input").val() * 1;
        var a = $("#tprice").html();
        $("#tprice").html((a - danjia * num).toFixed(2));
        var actualPay = $("#tprice").html() * 1;
        $("#actualPay").html(actualPay.toFixed(2));
        $(this).parent().parent().parent().parent().remove();
        if ($(".price").length < 1) {
            $("#payDetail").remove();
            $("#groupBtn").remove();
            $("#prompt").show();
        }
        writecache();
    });

    //当页面加载完的时候给window加载监听器
//    window.addEventListener("pagehide", myUnloadHandler, false);

    function myUnloadHandler(evt) {
        var content = "";
        $('.price').each(function (index) {
            var num = parseInt($(this).parent().parent().next().children(".placeholder").children(".weui-count").children("input").val() || "0");
            var cprice = $(this).text().substring(1);
            var price = $(this).prev().prev().prev().val();
            var pid = $(this).prev().prev().prev().prev().val();
            var name = $(this).prev().prev().html();
            var enname = $(this).prev().val();
            if (index == $(".price").length - 1) {
                content += '{"name":"' + name + '","num":"' + num + '","pid":"' + pid + '","cprice":"' + cprice + '","price":"' + price + '","enname":"' + enname + '"}';
            } else {
                content += '{"name":"' + name + '","num":"' + num + '","pid":"' + pid + '","cprice":"' + cprice + '","price":"' + price + '","enname":"' + enname + '"},';
            }
        });
        var json = '{"list":[' + content + ']}';
        window.localStorage.setItem("list${mach}", json);
    }

    //获取缓存
    function load() {
        var storage = JSON.parse(localStorage.getItem("list${mach}"));
        console.log(storage);
        if (storage == null) {
            return;
        }
        var list = storage.list;
        console.log(list);
        if (list.length == 0) {
            return;
        }
        for (var i = 0; i < list.length; i++) {
            $('#payDetail').before(function () {
                var div = '<div class="orderBoxs" style="margin-top:10px;">' +
                        '<div class="weui-flex" style="background-color:white; margin-top: 10px;">' +
                        '<div class="weui-flex__item">' +
                        '<div class="placeholder">' +
                        '<img src="'+list[i].imageurl+'" width="100%" height="100%" />' +
                        '</div>' +
                        '</div>' +
                        '<div class="weui-flex__item weui-flex justify align">' +
                        '<div>' +
                        '<input type="hidden" value="' + list[i].pid + '" />' +
                        '<input type="hidden" value="' + list[i].price + '" />' +
                        '<p class="name">' + list[i].name + '</p>' +
                        '<input type="hidden" value="' + list[i].enname + '" />' +
                        '<p class="price">￥' + list[i].cprice + '</p>' +
                        '</div>' +
                        '</div>' +
                        '<div class="weui-flex__item weui-flex justify align">' +
                        '<div class="placeholder" style="height: 100%;">' +
                        '<div style="height: 20%;"></div>' +
                        '<div class="weui-count">' +
                        '<a class="weui-count__btn weui-count__decrease"></a>' +
                        '<input class="weui-count__number" readonly="readonly" type="number" value="' + list[i].num + '" />' +
                        '<a class="weui-count__btn weui-count__increase"></a>' +
                        '</div>' +
                        '<div style="padding-top: 15px; padding-right: 6px;">' +
                        '<img class="delete" src="images/laji.png" style="float: right;margin-right: 20%;" />' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '</div>';
                return div;
            });
        }

        //测试支付
        document.querySelector('#wxPay').onclick = function () {
            localStorage.setItem("pagename","paypage");
            var param = {};

            var goodsinfo = "";
            var total = 0;

            $('.price').each(function (index) {
                var counts = parseInt($(this).parent().parent().next().children(".placeholder").children(".weui-count").children("input").val() || "0");
                var cprice = $(this).text().substring(1);
                var price = $(this).prev().prev().prev().val();
                var pid = $(this).prev().prev().prev().prev().val();
                var productname = $(this).prev().prev().html();
                var description = $(this).prev().val();

                if (index == $(".price").length - 1) {
                    goodsinfo += '{"counts":"' + counts + '","cprice":"' + cprice + '","price":"' + price + '","pid":"' + pid + '","productname":"' + productname + '","description":"' + description + '"}';
                } else {
                    goodsinfo += '{"counts":"' + counts + '","cprice":"' + cprice + '","price":"' + price + '","pid":"' + pid + '","productname":"' + productname + '","description":"' + description + '"},';
                }
                total += counts;
            });

            var goodsinfos = '[' + goodsinfo + ']';
            param.accesstoken = "${accesstoken}";
            param.goodsinfo = goodsinfos;
            param.total = total;
            param.tprice = $("#tprice").html();
            param.acprice = $("#actualPay").html();
            param.paymode = "1";
            param.openid = "${openid}";
            param.machserial = "${mach}";
            param.tradetype = "JSAPI";
            console.log(param);

            $.ajax({
                type: 'POST',
                url: '${url}/order/order.do',
                cache: false,
                dataType: 'json',
                data: param,
                success: function (result) {
                    console.log(result);
                    if (result.success == false) {
                        console.log(result);
                        $.toast(result.msg, "text");
                        setTimeout(function () {
                            window.location.href = '/index.do';
                        }, 2500);
                    } else {
                        if (result.code == 0) {
                            wx.chooseWXPay({
                                timestamp: result.body.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                                nonceStr: result.body.nonceStr, // 支付签名随机串，不长于 32 位
                                package: result.body.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                                signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                                paySign: result.body.paySign, // 支付签名
                                success: function (res) {
                                    var param = {};
                                    param.openid = '${openid}';
                                    param.accesstoken = '${accesstoken}';
                                    param.mach = '${mach}';
                                    param.orderid = result.orderid;
                                    param.outtradeno = result.outtradeno;
                                    param.status = "FINISH";
                                    $.ajax({
                                        type: 'POST',
                                        url: '${url}/order/orderstate.do',
                                        cache: false,
                                        dataType: 'json',
                                        data: param,
                                        success: function (result) {
                                            localStorage.removeItem("list${mach}");
                                            localStorage.setItem("lucky${openid}",parseInt(localStorage.getItem("lucky${openid}"))+1);
                                            $.toast("操作成功");
                                            setTimeout(function () {
                                                var param = {};
                                                param.openid = '${openid}';
                                                param.accesstoken = '${accesstoken}';
                                                param.mach = '${mach}';
                                                $.submitFormPost('/myorder.do', param, 'POST');
                                            }, 1000);
                                        },
                                        error: function (result) {
                                            alert("修改订单状态error");
                                        }
                                    });
                                },
                                error: function (res) {
                                    var param = {};
                                    param.openid = '${openid}';
                                    param.accesstoken = '${accesstoken}';
                                    param.mach = '${mach}';
                                    param.orderid = result.orderid;
                                    param.outtradeno = result.outtradeno;
                                    param.status = "FAIL";
                                    $.ajax({
                                        type: 'POST',
                                        url: '${url}/order/orderstate.do',
                                        cache: false,
                                        dataType: 'json',
                                        data: param,
                                        success: function (result) {
                                            $.toast("支付失败", "forbidden");
                                            setTimeout(function () {
                                                $(".orderBoxs").remove();
                                                window.localStorage.removeItem("list${mach}");
                                                var param = {};
                                                param.openid = '${openid}';
                                                param.accesstoken = '${accesstoken}';
                                                param.mach = '${mach}';
                                                $.submitFormPost('/myorder.do', param, 'POST');
                                            }, 1000);
                                        },
                                        error: function (result) {
                                            alert("修改订单状态error");
                                        }
                                    });
                                },
                                cancel: function (res) {
                                    var param = {};
                                    param.openid = '${openid}';
                                    param.accesstoken = '${accesstoken}';
                                    param.mach = '${mach}';
                                    param.orderid = result.orderid;
                                    param.outtradeno = result.outtradeno;
                                    param.status = "UNPAID";
                                    $.ajax({
                                        type: 'POST',
                                        url: '${url}/order/orderstate.do',
                                        cache: false,
                                        dataType: 'json',
                                        data: param,
                                        success: function (result) {
                                            $.submitFormPost('/myorder.do', param, 'POST');
                                        },
                                        error: function (result) {
                                            alert("修改订单状态error");
                                        }
                                    });
                                }
                            });
                        } else {
                            $.alert(result.msg, "警告！");
                            window.localStorage.removeItem('list${mach}');
                        }
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(123);
                    alert('连接错误');
                }
            });
        };

        wx.error(function (res) {
            console.log(res);
        });

        $("#main").on("click", function () {
            var param = {};
            param.openid = '${openid}';
            param.accesstoken = '${accesstoken}';
            param.state = '${mach}';
            $.submitFormPost('/weixin.do', param, 'POST');
        });

        $("#my").on("click", function () {
            var param = {};
            param.openid = '${openid}';
            param.accesstoken = '${accesstoken}';
            param.mach = '${mach}';
            $.submitFormPost('/my.do', param, 'POST');
        });

        //返回
        $('#back').click(function () {
            var param = {};
            param.openid = '${openid}';
            param.accesstoken = '${accesstoken}';
            param.state = '${mach}';
            $.submitFormPost('/weixin.do', param, 'POST');
        });
    }
</script>
</body>
</html>